package com.wanban.download.base

import io.reactivex.Flowable
import io.reactivex.disposables.Disposable
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
import java.util.concurrent.LinkedBlockingQueue
import java.util.concurrent.ThreadPoolExecutor
import java.util.concurrent.TimeUnit

abstract class BaseDownloadInterface(isSingleThread: Boolean) {

    // 回调的时间间隔
    protected var intervalTime = 1000L
    // 多线程下载的速度
    @Volatile
    protected var currentDownloadSpeed = 0L
    // 从各个线程返回的progress的大小
    @Volatile
    protected var currentDownloadLength = 0L
    // 下载是否被中断
    @Volatile
    protected var isInterrupted = false
    // 按时间间隔回调
    private var progressDisposable: Disposable? = null
    // 线程池
    protected val executors: ExecutorService = if(isSingleThread) {
        Executors.newSingleThreadExecutor()
    } else {
//        val coreNum = Runtime.getRuntime().availableProcessors()
//        val maxEveryTaskThreadNum = if (coreNum <= 2) { // 少于2核心，每个下载最多4
//            3
//        } else  { // 4核，8核
//            coreNum
//        }
        ThreadPoolExecutor(3, 3,
            5000L, TimeUnit.MILLISECONDS,
            LinkedBlockingQueue())
    }

    open fun cancel() {
        isInterrupted = true
        cancelProgress()
        executors.shutdownNow()
        currentDownloadSpeed = 0
    }

    open fun startDownload(totalLength:Long = 0) {}

    abstract fun onProgressCallback()

    protected fun cancelProgress(){
        progressDisposable?.dispose()
    }
    // 启动回调
    protected fun startProgressCallback(){
        if (progressDisposable?.isDisposed == false) {
            progressDisposable?.dispose()
        }
        progressDisposable = Flowable.interval(intervalTime, TimeUnit.MILLISECONDS)
            .subscribe({
                if (isInterrupted) return@subscribe
                onProgressCallback()
            }, {
                it?.printStackTrace()
            })
    }
}